package main

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
	"html/template"
	"log"
	"net/http"
	//"strings"
)

const (
	salt = "mkf_12@#1*"
)

func sayhello(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	if r.Method == "GET" {
		fmt.Fprintf(w, "hello your method is get")
		return
	} else if r.Method == "POST" {
		fmt.Fprintf(w, "cannot use post")
		return
	}
}
func checkUser(user string, passwd string) (ret bool) {
	session, err := mgo.Dial("127.0.0.1")
	if nil != err {
		fmt.Println("fail to dial localhost")
		return false
	}
	c := session.DB("user").C("passwd")
	h1 := md5.New()
	h1.Write([]byte(salt + passwd))
	hash := hex.EncodeToString(h1.Sum(nil))

	getPass := make(map[string]string)
	err = c.Find(bson.M{"user": user}).Select(bson.M{"passwd": 1, "_id": 0}).One(&getPass)
	if getPass["passwd"] != string(hash) {
		return false
	} else {
		return true
	}

}
func registerUser(user string, passwd string) (ret bool) {
	session, err := mgo.Dial("127.0.0.1")
	if nil != err {
		fmt.Println("fail to dial localhost")
		return false
	}
	c := session.DB("user").C("passwd")
	h1 := md5.New()
	h1.Write([]byte(salt + passwd))
	hash := hex.EncodeToString(h1.Sum(nil))
	getPass := make(map[string]string)
	err = c.Find(bson.M{"user": user}).Select(bson.M{"passwd": 1, "_id": 0}).One(&getPass)
	if len(getPass) != 0 {
		return false
	} else {
		getPass["passwd"] = string(hash)
		getPass["user"] = user
		_, err = c.Upsert(bson.M{"user": user}, getPass)
		if nil != err {
			fmt.Println("insert mgo fail!")
			return false
		}
		return true
	}
}
func login(w http.ResponseWriter, r *http.Request) {
	if r.Method == "GET" {
		t, _ := template.ParseFiles("./login.html")
		t.Execute(w, nil)
	} else {
		r.ParseForm()

		ret := checkUser(string(r.Form["username"][0]), string(r.Form["password"][0]))
		if ret {
			fmt.Fprintf(w, "login success")
		} else {
			fmt.Fprintf(w, "invalid user or passwd")
		}
	}
}
func register(w http.ResponseWriter, r *http.Request) {
	if r.Method == "GET" {
		t, _ := template.ParseFiles("./register.html")
		t.Execute(w, nil)
	} else {
		r.ParseForm()
		ret := registerUser(r.Form["username"][0], r.Form["password"][0])
		if ret {
			fmt.Fprintf(w, "register success")
		} else {
			fmt.Println("register fail")
		}

	}
}

func main() {
	http.HandleFunc("/", sayhello)
	http.HandleFunc("/login", login)
	http.HandleFunc("/register", register)
	err := http.ListenAndServe("127.0.0.1:8080", nil)
	if nil != err {
		log.Fatal("listen and server", err)
	}
}
